<template>
  <view class="container">
    <!-- 顶部搜索框 -->
    <view class="search-container">
      <view class="search-box">
        <view class="search-icon">
          <uni-icons type="search" size="24" color="#999"></uni-icons>
        </view>
        <input class="search-input" placeholder="搜索音频" placeholder-style="color: #999;" @confirm="handleSearch" />
      </view>
    </view>

    <!-- 音频列表 -->
    <view class="audio-list">
      <view v-for="(item, index) in audioList" :key="item.id || index" class="audio-item" :class="{ 'active-item': activeIndex === index }" @click="handleSetting(index)">
        <view class="audio-content">
			<view class="audio-header">
				<view class="audio-title">{{ item.name }}</view>
				<view class="time-display">
				  {{ formatTime(item.currentTime) }} / {{ formatTime(item.duration) }}
				</view>
			</view>
			
			<view class="play-btn" @click.stop="togglePlayPause(index)">
				<image :src="item.isPlaying ? '/static/images/pause.png' : '/static/images/play.png'" class="play-icon" />
			</view>
		</view>
		<!-- , {'expanded':item.isPlaying} -->
		<view :class="['dropDown', {'expanded':item.isPlaying}]">
			<!-- <view :class="['progress-bar-container', {'bar-container':item.isPlaying}]" class="" @touchstart.stop="handleProgressTouchStart(index, $event)"
			@touchmove.stop="handleProgressTouchMove(index, $event)" @touchend.stop="handleProgressTouchEnd(index, $event)">
			
				 <view class="progress-bar" >
				  <view class="progress"  :style="{ width: item.progress + '%' }">
					  <view class="progress-indicator" ></view>
				  </view>
				</view>
			</view> -->
			<!-- <MusicPlayer ref="player" :url="url" @play="togglePlayPause(index)"></MusicPlayer> -->
			
		<!-- 	{{item.progress}}
			{{ progressPercent }} -->
			<view :class="['progress-bar-container', {'bar-container':item.isPlaying}]">
				<slider
					v-if="item.isPlaying"
					:block-size="16"
					:value="item.progress" 
					@change="handleProgressChange(index, $event)" 
					@touchstart="handleProgressTouchStart(index)" 
					@touchmove="handleProgressTouchMove(index, $event)"
					@touchend="handleProgressTouchEnd(index)"
					min="0" max="100"
					activeColor="#FF4949" 
					backgroundColor="#eee"
				/>
			</view>
		</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {onLoad , onUnload, onHide} from '@dcloudio/uni-app'
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { getFfileQuery } from '@/api/common.js';


const activeIndex = ref(-1);
const audioList = ref([
	{
	  id: 1,
	  name: '录音1',
	  duration: '00:30', // 录音时长
	  date: '2025-06-04' // 录音日期
	},
]);
let currentAudioCtx = null;
let currentItemIndex = -1;
let isDragging = false; // 拖动状态标记

// let currentAudioCtx = null; // 当前音频实例
// let currentItemIndex = -1; // 当前播放项索引

// 页面加载
onLoad(async () => {
  const uid = uni.getStorageSync("userInfo")?.id;
  try {
    const res = await getFfileQuery({ uid });
    if (res.code !== 200) throw new Error('获取音频列表失败');
    
    audioList.value = res.data.map((item, index) => {
		
		return {
		  ...item,
		  isPlaying: false,
		  currentTime: 0,
		  duration: 0,
		  progress: 0,
		  isLoading: false,
		}
	})
	audioList.value.forEach((item, index) => {
		playAudio(index, true);
	})
  } catch (err) {
	  console.log("err", err)
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  }
});

const handleSetting = (index) => {
  const item = audioList.value[index];
  const params = { id: item.id };

  const encodedParams = encodeURIComponent(JSON.stringify(params));
  const url = `/pages/audio_operation/audio_operation?params=${encodedParams}&dataValue=${JSON.stringify(item)}`;

  uni.showLoading({
    title: '跳转中...',
    mask: true
  });

  uni.navigateTo({
    url,
    success: () => {
      console.log('页面跳转成功');
    },
    fail: (err) => {
      console.error('页面跳转失败', err);
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      });
    },
    complete: () => {
      uni.hideLoading();
    }
  });
};
// 进度条触摸开始
const handleProgressTouchStart = (index) => {
  isDragging = true;
  const item = audioList.value[index];
  if (currentItemIndex === index && currentAudioCtx) {
    currentAudioCtx.pause(); // 拖动时暂停播放，提升体验
  }
};

// 进度条触摸移动
const handleProgressTouchMove = (index, e) => {
  if (!isDragging) return;
  const item = audioList.value[index];
  if (currentItemIndex === index && item.duration) {
    const percent = Math.max(0, Math.min(100, e.detail.value));
    item.progress = percent; // 实时更新进度显示
    const newTime = (percent / 100) * item.duration;
    currentAudioCtx?.seek(newTime); // 安全调用
  }
};

// 进度条触摸结束
const handleProgressTouchEnd = (index) => {
  isDragging = false;
  const item = audioList.value[index];
  if (currentItemIndex === index && currentAudioCtx) {
    currentAudioCtx.play(); // 恢复播放
  }
};

// 进度条值改变事件（保留用于键盘或鼠标拖动）
const handleProgressChange = (index, e) => {
  if (isDragging) return; // 避免触摸和值改变事件冲突
  const item = audioList.value[index];
  if (currentItemIndex === index && item.duration && currentAudioCtx) {
    const percent = Math.max(0, Math.min(100, e.detail.value));
    const newTime = (percent / 100) * item.duration;
    currentAudioCtx.seek(newTime);
  }
};


// 点击音频项处理
const handleItemClick = (index) => {
  // 如果点击当前播放项，切换暂停/播放
  if (index === currentItemIndex) {
    togglePlayPause(index);
  } else {
    // 点击其他项，停止当前并播放新项
    stopCurrentAudio();
  }
};

// 播放/暂停控制
const togglePlayPause = (index) => {
  const item = audioList.value[index];
  
  // 如果是首次播放或实例已销毁，创建新实例
  if (!currentAudioCtx || currentItemIndex !== index) {
    playAudio(index);
    return;
  }
  
  // 切换播放状态
  item.isPlaying = !item.isPlaying;
  
  if (item.isPlaying) {
    currentAudioCtx.play();
  } else {
    currentAudioCtx.pause();
  }
};
// 初始化播放
const playAudio = (index,type) => {
	stopCurrentAudio(); 
	console.log("audioList.value", audioList.value)
   const item = audioList.value[index];
   console.log("item", item)
   
    if (!item.url) return;
  
  // 停止并销毁当前音频实例
  stopCurrentAudio();
  
  // 更新当前播放项索引
  currentItemIndex = index;
  activeIndex.value = index;
  
  // 创建新音频实例
  currentAudioCtx = uni.createInnerAudioContext();
  currentAudioCtx.src = item.url;
  
  // 设置加载状态
  item.isLoading = true;
  
  // 监听事件
  currentAudioCtx.onCanplay(() => {
    item.duration = Math.floor(currentAudioCtx.duration);
	if (type) return;
    item.isPlaying = true;
    item.isLoading = false;
    currentAudioCtx.play();
  });
  
   currentAudioCtx.onTimeUpdate(() => {
      if (item.duration === 0) return;
      
      // 计算进度并限制在 0-100 范围内
      const progress = (currentAudioCtx.currentTime / item.duration) * 100;
      item.progress = Math.max(0, Math.min(100, Math.floor(progress))); // 关键修复
      item.currentTime = Math.floor(currentAudioCtx.currentTime);
    });
  
  currentAudioCtx.onEnded(() => {
    stopCurrentAudio();
  });
  
  currentAudioCtx.onError((err) => {
    console.error('音频播放错误:', err);
    item.isLoading = false;
    stopCurrentAudio();
  });
};

// 停止当前音频
const stopCurrentAudio = () => {
	console.log('stopCurrentAudio called'); // 关键日志
    if (currentAudioCtx) {
      currentAudioCtx.pause(); // 暂停播放
      currentAudioCtx.destroy(); // 销毁实例
      currentAudioCtx = null; // 置空引用
    }
    // 重置状态
    currentItemIndex = -1;
    activeIndex.value = -1;
    audioList.value.forEach(item => {
      item.isPlaying = false;
      item.progress = 0;
    });
};

// // 进度条拖动处理
// const handleProgressChange = (index, e) => {
//    const item = audioList.value[index];
//     if (currentItemIndex === index && item.duration && currentAudioCtx) {
//       // 拖动时限制值在 0-100 之间
//       const percent = Math.max(0, Math.min(100, e.detail.value)); 
//       const newTime = (percent / 100) * item.duration;
//       currentAudioCtx.seek(newTime);
//     }
// };

// 格式化时间
const formatTime = (seconds) => {
  if (isNaN(seconds) || seconds === 0) return '00:00';
  const min = Math.floor(seconds / 60).toString().padStart(2, '0');
  const sec = Math.floor(seconds % 60).toString().padStart(2, '0');
  return `${min}:${sec}`;
};

// onUnmounted(stopCurrentAudio);
// 页面卸载清理
onUnload(() => {
	console.log("zhixing")
	stopCurrentAudio()
});
onHide(() => {
	stopCurrentAudio()
})
</script>

<style lang="scss" scoped>
	
.dropDown {
	height: 10rpx;
	margin-top: 30rpx;
	margin-top: 20rpx;
	// transform-origin: left center;
	// transition:transform 0.3s ease-in-out;
	transition:height 0.2s ease-in-out;
	// transform: scaleX(0);
	// overflow: hidden;
}

.progress-bar-container {
	transform-origin: right center;
	transition:transform 1s ease-in-out;
	transform: scaleX(0);
}
.progress-bar-container.bar-container {
	transform: scaleX(1);
}
.dropDown.expanded {
	height: 50rpx;
	// transform: scaleX(1);
}

.container {
  padding-top: 80rpx;
  background-color: #f9f9f9;
  padding-bottom: 120rpx;
}

.search-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #ffffff;
  padding: 24rpx 32rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 48rpx;
  height: 72rpx;
  padding: 0 28rpx;
  transition: all 0.3s ease;
  border: 1rpx solid transparent;

  &:focus-within {
    border-color: rgba(0, 122, 255, 0.3);
    background-color: #fff;
    box-shadow: 0 0 0 4rpx rgba(0, 122, 255, 0.1);
  }
}

.search-icon {
  padding-right: 16rpx;
  color: #999;
}

.search-input {
  flex: 1;
  border: none;
  background: transparent;
  font-size: 28rpx;
  color: #333;
  height: 100%;
}

.audio-list {
	margin-top: 20rpx;
	padding: 24rpx 32rpx;
}

.audio-item {
  margin-top: 24rpx;
  background: #ffffff;
  border-radius: 28rpx;
  padding: 36rpx;
  padding-bottom: 0;
  position: relative;
  transition: all 0.3s ease;
}

.audio-content {

  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}



.audio-title {
  font-size: 36rpx;
  color: #333;
  font-weight: 500;
  max-width: 400rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.more-btn {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;

  &:hover {
    background-color: #f5f5f5;
  }
}

.progress-bar {
  height: 16rpx;
  background-color: #f0f0f0;
  border-radius: 6rpx;
}

.progress {
  height: 100%;
  background: linear-gradient(90deg, #007AFF 0%, #34AADC 100%);
  transition: width 0.01s linear;
  border-radius: 6rpx;
  position: relative;
}

.progress-indicator {
  position: absolute;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  width: 28rpx;
  height: 28rpx;
  background:red;
  border-radius: 50%;
  cursor: pointer;
  z-index: 99999;
}

.time-display {
  font-size: 24rpx;
  color: #999;
  display: flex;
  align-items: center;
}

.control-buttons {
  display: flex;
  gap: 32rpx;
  align-items: center;
  justify-content: center;
}

.control-btn {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0.8;
  transition: all 0.2s ease;

  &:hover {
    opacity: 1;
    transform: scale(1.08);
  }

  &:active {
    transform: scale(0.92);
    transition: transform 0.1s ease;
  }

  .control-icon {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}

.play-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 86rpx;
  height: 86rpx;
  background-color: #d3d3d3;
  background: linear-gradient(135deg, #007AFF 0%, #34AADC 100%);
  border-radius: 50%;
  box-shadow: 0 8rpx 24rpx rgba(0, 122, 255, 0.3);
  transition: all 0.3s ease;

  .play-icon {
    width: 44rpx;
    height: 44rpx;
  }

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 10rpx 28rpx rgba(0, 122, 255, 0.4);
  }

  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 16rpx rgba(0, 122, 255, 0.5);
  }
}

.delete-btn {
  &:hover {
    background-color: rgba(255, 59, 48, 0.1);
  }
}

.speed-control {
  padding: 12rpx 24rpx;
  background-color: #f5f5f5;
  border-radius: 20rpx;
  font-size: 26rpx;
  color: #666;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 12rpx;
  transition: all 0.2s ease;

  &:hover {
    background-color: #f0f0f0;
  }
}

.speed-text {
  display: flex;
  align-items: center;
}
/* 修改 slider 组件的高度（uni-app 中需使用深度选择器） */
:deep(.uni-slider-handle-wrapper) {
  height: 8rpx; /* 示例高度，可根据需求调整（rpx 为响应式单位） */
}

</style>